<!--
 * @Author: Liz.Zheng
 * @Date: 2021-11-15 20:08:40
 * @LastEditTime: 2023-02-20 10:21:42
 * @Description: 添加楼宇
 * @Motto: Write the code. Change the world.
-->

<template>
  <a-drawer
    :title="title"
    :maskClosable="false"
    :visible="visible"
    :destroyOnClose="true"
    :width="$store.getters.isMobile ? 300 : 450"
    :body-style="{
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
    }"
    @close="handleClose"
  >
    <section class="content">
      <a-form layout="vertical">
        <a-form-item label="楼宇编号：" v-bind="validateInfos.buildingNo">
          <a-input
            placeholder="请输入..."
            v-model:value="formData.buildingNo"
          />
        </a-form-item>
        <a-form-item label="楼宇名称：" v-bind="validateInfos.buildingName">
          <a-input
            placeholder="请输入..."
            v-model:value="formData.buildingName"
          />
        </a-form-item>
        <template v-if="!showBuildingArr">
          <a-form-item label="楼层：" v-bind="validateInfos.groundCount">
            <a-input
              addon-before="地面"
              addon-after="层"
              placeholder="请输入..."
              v-model:value="formData.groundCount"
            />
          </a-form-item>
          <a-form-item v-bind="validateInfos.undergroundCount">
            <a-input
              addon-before="地下"
              addon-after="层"
              placeholder="请输入..."
              v-model:value="formData.undergroundCount"
            />
          </a-form-item>
          <a-form-item label="每层房间数：" v-bind="validateInfos.roomCount">
            <a-input
              placeholder="请输入..."
              v-model:value="formData.roomCount"
            />
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              class="w-100p"
              size="large"
              :disabled="genDisabled"
              @click="genBuildingArr"
              :loading="genLoading"
              >生成</a-button
            >
          </a-form-item>
        </template>

        <a-card
          v-if="showBuildingArr"
          size="small"
          :bordered="false"
          title="楼层"
          :bodyStyle="{ background: '#f7f7f7' }"
        >
          <template #extra>
            <a-button type="link" @click="reGenBuildingArr">{{
              $t("重新生成")
            }}</a-button>
          </template>
          <section class="building-total">共{{ buildingArr.length }}层</section>
          <section class="floor-list">
            <div
              v-for="(floor, floorIndex) of buildingArr"
              :key="floor.number"
              class="floor-module"
            >
              <div class="list-item">
                <div class="title">
                  <cu-icon class="icon" type="org-tree-louceng" />
                  <span>{{ floor.name }}</span>
                </div>
                <div class="opt">
                  <a-popconfirm
                    @confirm="handleCustomTitleConfirm({ floorIndex })"
                    @cancel="handleCustomTitleCancel"
                  >
                    <template #icon>
                      <FontSizeOutlined />
                    </template>
                    <template #title>
                      <a-input
                        size="small"
                        v-model:value="customTitle"
                        placeholder="自定义标题"
                      />
                    </template>
                    <EditOutlined />
                  </a-popconfirm>
                  <MinusOutlined @click="handleFloorRemove({ floorIndex })" />
                </div>
              </div>
              <template v-if="floor.roomList && floor.roomList.length">
                <div
                  class="list-item room-item"
                  v-for="(room, roomIndex) of floor.roomList"
                  :key="room.number"
                >
                  <div class="title">
                    <cu-icon class="icon" type="org-tree-fangjian" />
                    <span>{{ room.name }}</span>
                  </div>
                  <div class="opt">
                    <a-popconfirm
                      @confirm="
                        handleCustomTitleConfirm({ floorIndex, roomIndex })
                      "
                      @cancel="handleCustomTitleCancel"
                    >
                      <template #icon>
                        <FontSizeOutlined />
                      </template>
                      <template #title>
                        <a-input
                          size="small"
                          v-model:value="customTitle"
                          placeholder="自定义标题"
                        />
                      </template>
                      <EditOutlined />
                    </a-popconfirm>
                    <MinusOutlined
                      @click="handleFloorRemove({ floorIndex, roomIndex })"
                    />
                  </div>
                </div>
              </template>
            </div>
          </section>
        </a-card>
      </a-form>
    </section>
    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="handleClose">取消</a-button>
      <a-button type="primary" @click.prevent="handleSubmit">确定</a-button>
    </div>
  </a-drawer>
</template>

<script>
import { computed, defineComponent, reactive, ref, watch } from "vue";
import { Form, message } from "ant-design-vue";
import utils from "../../../../common/utils/utils";
import {
  EditOutlined,
  MinusOutlined,
  FontSizeOutlined,
} from "@ant-design/icons-vue";

const useForm = Form.useForm;

export default defineComponent({
  name: "ProjectBuildingAdd",
  components: { EditOutlined, MinusOutlined, FontSizeOutlined },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    sort: {
      type: Number,
      default: 0,
    },
    detail: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  setup(props, context) {
    const formData = reactive({
      buildingNo: "",
      buildingName: "",
      groundCount: "",
      undergroundCount: "",
      roomCount: "",
    });
    const rulesRef = reactive({
      buildingNo: [
        {
          required: false,
          validator: (rules, value) => numberValidator(value),
          trigger: "change",
        },
      ],
      buildingName: [
        {
          required: true,
          message: "楼宇名称是必填",
          trigger: "blur",
        },
      ],
      groundCount: [
        {
          required: true,
          validator: (rules, value) => numberValidator(value),
          trigger: "change",
        },
      ],
      undergroundCount: [
        {
          required: true,
          validator: (rules, value) =>
            numberValidator(value, "undergroundCount"),
          trigger: "change",
        },
      ],
      roomCount: [
        {
          validator: (rules, value) => numberValidator(value),
          trigger: "change",
        },
      ],
    });
    const numberValidator = async (value, type) => {
      const reg = /^[0-9]*$/;
      if (!reg.test(value)) {
        return Promise.reject("请输入整数");
      }
      if ("undergroundCount" === type && value > 10) {
        return Promise.reject("地下楼层不能超过10层");
      }
      return Promise.resolve();
    };
    const { validateInfos, validate } = useForm(formData, rulesRef);

    // 生成按钮可点击
    const genDisabled = computed(
      () =>
        !(
          formData.buildingName &&
          formData.groundCount &&
          formData.undergroundCount
        )
    );

    // 生成楼层数组
    const buildingArr = ref([]);
    const genLoading = ref(false);
    const genBuildingArr = () => {
      validate().then(() => {
        genLoading.value = true;
        const { groundCount, undergroundCount } = formData;
        let ugList = [];
        let gList = [];
        // 地下
        for (let i = 1; i <= undergroundCount; i++) {
          const number = `B${i}`;
          ugList.push({
            name: number,
            number: -i,
            // sort: undergroundCount - i,
            sort: 0,
          });
        }
        // 地面
        for (let i = groundCount; i--; ) {
          const number = `${i + 1}`;
          gList.push({
            name: number,
            number: Number(number),
            // sort: i + Number(undergroundCount),
            roomList: getRoomList(number),
            sort: 0,
          });
        }

        buildingArr.value = [...gList, ...ugList];
        // console.log("------------buildingArr", buildingArr.value);
        genLoading.value = false;
        showBuildingArr.value = true;
      });
    };
    // 生成房间号
    const getRoomList = (prefix) => {
      let list = [];
      if (formData.roomCount) {
        let length = String(formData.roomCount).length; //几位整数
        length = length == 1 ? 2 : length;
        for (let i = 1; i <= formData.roomCount; i++) {
          const number = prefix + utils.prefixInteger(i, length);
          list.push({
            // sort: formData.roomCount - i + 1,
            sort: 0,
            name: number,
            number: Number(number),
          });
        }
      }
      return list;
    };

    const showBuildingArr = ref(false);
    // 重新生成
    const reGenBuildingArr = () => {
      formData.groundCount = "";
      formData.undergroundCount = "";
      formData.roomCount = "";
      showBuildingArr.value = false;
      buildingArr.value = [];
    };

    // 自定义标题
    const customTitle = ref("");
    const handleCustomTitleConfirm = ({ floorIndex, roomIndex }) => {
      if (!customTitle.value) {
        return;
      }
      let current =
        roomIndex != undefined
          ? buildingArr.value[floorIndex].roomList[roomIndex]
          : buildingArr.value[floorIndex];
      current.name = `${current.number}（${customTitle.value}）`;
      customTitle.value = "";
    };
    const handleCustomTitleCancel = () => {
      customTitle.value = "";
    };
    // 移除房间、楼层
    const handleFloorRemove = ({ floorIndex, roomIndex }) => {
      if (roomIndex || roomIndex == 0) {
        // 移除房间
        buildingArr.value[floorIndex].roomList.splice(roomIndex, 1);
      } else {
        // 移除楼层
        buildingArr.value.splice(floorIndex, 1);
      }
    };

    const handleClose = () => {
      context.emit("cancel");
    };
    const handleSubmit = () => {
      if (!formData.buildingName || !buildingArr.value.length) {
        message.warning("请先生成楼层信息~");
        return;
      }
      let buildingData = {
        name: formData.buildingName,
        number: formData.buildingNo,
        sort: props.sort,
        layerList: buildingArr.value,
      };
      console.log("buildingData", buildingData);
      context.emit("confirm", buildingData);
    };

    const title = computed(() => (props.detail ? "编辑楼宇" : "添加楼宇"));
    watch(
      () => props.visible,
      (val) => {
        if (val) {
          if (props.detail) {
            // 编辑楼宇
            formData.buildingName = props.detail.name;
            formData.buildingNo = props.detail.number;
            buildingArr.value = props.detail.layerList;
            showBuildingArr.value = true;
          }
        } else {
          resetFormData();
          showBuildingArr.value = false;
          buildingArr.value = [];
        }
      }
    );

    const resetFormData = () => {
      formData.buildingNo = "";
      formData.buildingName = "";
      formData.groundCount = "";
      formData.undergroundCount = "";
      formData.roomCount = "";
    };
    return {
      title,
      formData,
      validateInfos,
      genDisabled,
      buildingArr,
      showBuildingArr,
      customTitle,
      genLoading,
      handleClose,
      handleSubmit,
      genBuildingArr,
      reGenBuildingArr,
      handleCustomTitleConfirm,
      handleCustomTitleCancel,
      handleFloorRemove,
    };
  },
});
</script>

<style lang="less" scoped>
.content {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
  .building-total {
    height: 40px;
    line-height: 40px;
    vertical-align: middle;
    color: #999;
    border-bottom: 1px solid #f1f1f1;
  }
  .floor-list {
    .floor-module {
      .list-item {
        height: 40px;
        margin: 10px 0;
        background: #fff;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        overflow: hidden;
        padding: 0 15px;
        box-sizing: border-box;
        .title {
          color: rgba(0, 0, 0, 0.8);
          font-weight: bold;
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          word-break: break-all;
          display: flex;
          align-items: center;
          .icon {
            font-size: 18px;
            margin-right: 4px;
          }
        }
        .opt {
          display: flex;
          width: 40px;
          align-items: center;
          justify-content: space-between;
          cursor: pointer;
          color: @primary-color;
        }
      }
      .room-item {
        margin-left: 20px;
      }
    }
  }
}
</style>
